<template>
  <div>
    <textarea class="textarea"
              @input="oninput"
              v-model="desc"
              rows="8"
              placeholder="这一刻的想法"></textarea>

    <text class="input-hint">已输入{{len}}/140字</text>

    <div class="bg-white p-1"
         v-if="type === 1">
      <div class="flex-row">
        <div v-for="(img, index) in images"
             :key="index">
          <image class="dynamic-img"
                 :src="img"
                 @click="imagePreview(index)"></image>

          <text class="icon delete-btn"
                @click="deleteImage(index)">&#xe69e;</text>
        </div>

        <text class="icon add-btn"
              v-if="imagesLen < 9"
              @click="selectPicture">&#xe69f;</text>

      </div>

    </div>

    <div class="bg-white p-3"
         v-if="type === 2">
      <image class="video-thumb"
             resize="cover"
             :src="videoThumb"
             @click="videoPreview"></image>

      <text class="icon icon-play"
            @click="videoPreview">&#xe6cc;</text>

      <text class="record-btn"
            @click="selectCamera">重新拍摄</text>
    </div>

    <div class="bg-white p-3 flex-row">
      <text class="icon small text-muted">&#xeb95;</text>
      <text class="mini text-muted flex">{{shootAddress}}</text>
    </div>

    <vm-button class="mt-3"
               text="发布"
               @buttonClicked="submit"></vm-button>

    <wxc-dialog title="提示"
                content="确定删除该图片？"
                :show="deleteShow"
                @wxcDialogCancelBtnClicked="wxcDialogCancelBtnClicked"
                @wxcDialogConfirmBtnClicked="wxcDialogConfirmBtnClicked">
    </wxc-dialog>
  </div>
</template>
<script>
import VmButton from '../../components/vm-button.vue'
import { WxcDialog } from 'weex-ui'

export default {
  components: { VmButton, WxcDialog },
  props: {},
  data() {
    return {
      type: 0,
      farm: {},
      desc: '',
      len: 0,
      images: [],
      video: '',
      videoThumb: '',
      deleteIndex: -1,
      deleteShow: false,

      shootAddress: '',
      lng: '',
      lat: ''
    }
  },
  computed: {
    gridImages() {
      const len = this.images.length
      const res = []
      res.push(this.images.slice(0, 3))
      if (len > 3) {
        res.push(this.images.slice(3, 6))
      }
      if (len > 6) {
        res.push(this.images.slice(6))
      }
      return res
    },
    imagesLen() {
      return this.images.length
    }
  },
  watch: {},
  created() {
    this.getParams()
    this.getUserLocation()
  },
  methods: {
    getParams() {
      this.$router.getParams().then(res => {
        this.farm = res.farm
        this.type = res.type
        if (this.type === 1) {
          this.images = res.images || []
        } else if (this.type === 2) {
          this.video = res.video
          this.videoThumb = res.thumb
        }
      })
    },
    getUserLocation() {
      this.$amap.getLocationOnce().then(res => {
        if (!res) { return }
        this.shootAddress = res.address
        this.lng = res.longitude
        this.lat = res.latitude
      }).catch(err => {
        console.log(err)
      })
    },
    onSelect() {
      if (this.type === 1) {
        this.selectPicture()
      } else if (this.type === 2) {
        this.selectCamera()
      }
    },
    selectPicture() {
      if (this.imagesLen >= 9) {
        return
      }
      this.$picture.pick({
        maxCount: 9 - this.imagesLen
      }).then(res => {
        const data = res || []
        this.images.push(...data)
      }).catch(err => {
        this.$notice.toast({ message: '选择图片失败，请重试！' })
      })
    },
    selectCamera() {
      this.$picture.video({}).then(({ type, data }) => {
        if (type === 'capture') {
          this.images = data
          this.type = 1
        } else {
          this.video = data[0] || ''
          this.thuvideoThumbmb = data[1] || ''
          this.type = 2
        }
      }).catch(err => {
        this.$notice.toast({ message: '视频拍摄失败，请重试！' })
      })
    },
    videoPreview() {
      this.$picture.videoPreview({ url: this.video })
    },
    imagePreview(index) {
      this.$image.preview({
        index,
        images: this.images,
      })
    },
    deleteImage(index) {
      this.deleteIndex = index
      this.deleteShow = true
    },
    wxcDialogCancelBtnClicked() {
      this.deleteShow = false
    },
    wxcDialogConfirmBtnClicked() {
      this.images.splice(this.deleteIndex, 1)
      this.deleteShow = false
    },
    oninput(event) {
      const val = event.value || ''
      this.len = val.length
    },
    submit() {
      if (this.type === 1) {
        this.uploadImage()
      } else if (this.type === 2) {
        this.uploadVideo()
      }
    },
    uploadImage() {
      this.$oss.uploadImage({
        files: this.images
      }).then(res => {
        const data = this.getPostData()
        data.images = res.length ? `["${res.join('","')}"]` : '[]'
        this.postDynamic(data)
      }).catch(err => {
        this.$notice.toast({ message: '上传图片失败，请重试' })
      })
    },
    uploadVideo() {
      Promise.all([
        this.$oss.uploadObject({
          files: [this.video]
        }),
        this.$oss.uploadImage({
          files: [this.videoThumb]
        })
      ]).then(res => {
        const data = this.getPostData()
        data.videoUrl = res[0][0]
        data.videoType = 'mp4'
        data.thumbnail = res[1][0]
        this.postDynamic(data)
      }).catch(err => {
        this.$notice.toast({ message: '上传视频失败，请重试' })
      })
    },
    postDynamic(data) {
      this.$http({
        method: 'POST',
        name: 'industrial.dynamic',
        data,
        errorMsg: '发布失败，请重试'
      }).then(res => {
        this.$notice.toast({ message: '发布成功' })
        // this.$router.back()
        // 发布成功后，跳转到鸡场秀
        this.$nav.open({ name: 'farm.show' })
        this.$router.finish()
      })
    },
    getPostData() {
      const topImg = this.farm.farmTopImages || []
      return {
        realName: this.farm.farmer || this.farm.contact,
        headImg: topImg.length ? topImg[0] : '',
        userId: this.farm.farmUserId,
        farmId: this.farm.id,
        productId: '',
        shootAddress: this.shootAddress,
        lng: this.lng,
        lat: this.lat,
        productIdArr: '',
        duration: '',
        title: '',
        textDescription: this.desc
      }
    }
  }
}
</script>
<style lang="scss" scoped>
@import "../../css/variables.scss";

.icon {
  font-family: alicon;
}
.text-muted {
  color: #999;
}
.text-right {
  text-align: right;
}
.mb-3 {
  margin-bottom: 30px;
}
.mt-3 {
  margin-top: 30px;
}
.small {
  font-size: 26px;
}
.mini {
  font-size: 24px;
}
.bg-white {
  background-color: #fff;
}
.p-3 {
  padding: 30px;
}
.p-1 {
  padding: 10px;
}
.pb-3 {
  padding-bottom: 30px;
}
.pb-1 {
  padding-bottom: 10px;
}
.flex-row {
  flex-direction: row;
  flex-wrap: wrap;
}
.flex {
  flex: 1;
}
.border-bottom {
  border-bottom-width: 1px;
  border-bottom-color: $border-color;
}

.textarea {
  font-size: 28px;
  width: 750px;
  height: 160px;
  padding: 20px;
  color: #333;
  background-color: #fff;
  tint-color: $primary;
}
.input-hint {
  color: #999;
  background-color: #fff;
  font-size: 26px;
  text-align: right;
  padding-bottom: 10px;
  padding-right: 10px;
  border-bottom-width: 1px;
  border-bottom-color: $border-color;
}
.dynamic-img {
  width: 218px;
  height: 218px;
  margin: 10px;
}
.video-thumb {
  width: 690px;
  height: 300px;
}
.icon-play {
  position: absolute;
  top: 140px;
  left: 320px;
  color: #fff;
  font-size: 80px;
}
.record-btn {
  position: absolute;
  top: 40px;
  right: 40px;
  padding: 15px;
  background-color: rgba(255, 255, 255, 0.8);
  border-width: 1px;
  border-color: $border-color;
  border-radius: 6px;
  font-size: 26px;
  color: #666;
}
.record-btn:active {
  background-color: #fff;
}
.delete-btn {
  position: absolute;
  top: 15px;
  right: 15px;
  padding: 5px;
  background-color: rgba(255, 255, 255, 0.5);
  border-width: 1px;
  border-color: $border-color;
  border-radius: 30px;
  font-size: 36px;
  color: $accent-light;
}
.add-btn {
  width: 218px;
  height: 218px;
  line-height: 218px;
  text-align: center;
  font-size: 80px;
  margin: 10px;
  background-color: $gray-200;
  color: $gray-500;
}
</style>
